package com.sc.study.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sc.study.client.GeneralClient;
import com.sc.study.client.SysConfigClient;
import com.sc.study.dto.SysUserDTO;
import com.sc.study.dto.VideoNoteDTO;
import com.sc.study.dto.VideoQueryDTO;
import com.sc.study.dto.ProjectFileDTO;
import com.sc.study.entity.StudyVideo;
import com.sc.study.entity.StudyVideoNote;
import com.sc.study.entity.StudyVideoRecord;
import com.sc.study.service.StudyVideoNoteService;
import com.sc.study.service.StudyVideoRecordService;
import com.sc.study.service.StudyVideoService;
import com.sc.study.service.impl.StudyVideoNoteServiceImpl;
import com.sc.study.service.impl.StudyVideoRecordServiceImpl;
import com.sc.study.service.impl.StudyVideoServiceImpl;
import com.sc.study.vo.ResultVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 研究视频控制器
 *
 * @author 徐赫阳
 * @date 2021/12/29
 */
@Api(description = "学习视频controller")
@RestController
@RequestMapping("/video")
public class StudyVideoController {
    /**
     * 服务对象
     */
    @Autowired
    private StudyVideoServiceImpl studyVideoService;
    @Autowired
    private GeneralClient generalClient;
    @Autowired
    private SysConfigClient sysConfigClient;
    @Autowired
    private StudyVideoNoteServiceImpl studyVideoNoteService;
    @Autowired
    private StudyVideoRecordServiceImpl recordService;
    @Autowired
    private StudyVideoNoteServiceImpl noteService;

    @ApiOperation("获取视频")
    @PostMapping("/getVideoList")
    public List<StudyVideo> getVideoList(@RequestBody VideoQueryDTO queryDTO){
        QueryWrapper<StudyVideo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .like(queryDTO.getTitle() != null, StudyVideo::getTitle,queryDTO.getTitle())
                .eq(queryDTO.getType() != null, StudyVideo::getType, queryDTO.getType())
                .isNull(queryDTO.getParentId() == null,StudyVideo::getParentId)
                .eq(queryDTO.getParentId() != null,StudyVideo::getParentId, queryDTO.getParentId());
        List<StudyVideo> list = studyVideoService.list(queryWrapper);
        list.forEach(val->{
            if(val.getFileId() != null){
                Object object = generalClient.getFileById(val.getFileId()).getData();
                ProjectFileDTO file = JSON.parseObject(JSON.toJSONString(object), ProjectFileDTO.class);
                val.setProjectFile(file);
            }
        });
        return list;
    }

    @ApiOperation("获取视频")
    @GetMapping("/getVideoById/{id}")
    public StudyVideo getVideoById(@PathVariable Integer id){
        StudyVideo video = studyVideoService.getById(id);
        Object object = generalClient.getFileById(video.getFileId()).getData();
        ProjectFileDTO file = JSON.parseObject(JSON.toJSONString(object), ProjectFileDTO.class);
        video.setProjectFile(file);
        return video;
    }

    @ApiOperation("保存")
    @PostMapping("/saveVideo")
    public Integer saveVideo(@RequestBody StudyVideo sysVideo, HttpServletRequest request) throws Exception{
        if(sysVideo.getId() == null){
            sysVideo.setCreatorId((Integer)request.getSession(true).getAttribute("user"));
        }else{
            sysVideo.setUpdaterId((Integer)request.getSession(true).getAttribute("user"));
        }
        studyVideoService.saveOrUpdate(sysVideo);
        return sysVideo.getId();
    }

    @ApiOperation("删除")
    @DeleteMapping(value = "/deleteVideo/{id}")
    public void deleteVideo(@PathVariable Integer id) throws Exception{
        QueryWrapper<StudyVideo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(StudyVideo::getParentId, id);
        List<StudyVideo> list = studyVideoService.list(queryWrapper);
        if (list != null && !list.isEmpty()){
            throw new Exception("请先删除下级内容");
        }else{
            studyVideoService.removeById(id);
        }
    }

    @ApiOperation("根据文件夹id获取其子视频")
    @GetMapping(value = "/getVideoByFolder/{id}")
    public List<StudyVideo> getVideoByFolder(@PathVariable Integer id) throws Exception{
        QueryWrapper<StudyVideo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(StudyVideo::getParentId, id)
                .eq(StudyVideo::getType,2);
        List<StudyVideo> list = studyVideoService.list(queryWrapper);
        list.forEach(val->{
            if(val.getFileId() != null){
                Object object = generalClient.getFileById(val.getFileId()).getData();
                ProjectFileDTO file = JSON.parseObject(JSON.toJSONString(object), ProjectFileDTO.class);
                val.setProjectFile(file);
            }
            QueryWrapper<StudyVideoRecord> recordWrapper = new QueryWrapper<>();
            recordWrapper.lambda()
                    .eq(StudyVideoRecord::getType,1)
                    .eq(StudyVideoRecord::getVideoId,val.getId());
            List<StudyVideoRecord> records = recordService.list(recordWrapper);
            QueryWrapper<StudyVideoRecord> recordWrapper2 = new QueryWrapper<>();
            recordWrapper2.lambda()
                    .eq(StudyVideoRecord::getType,2)
                    .eq(StudyVideoRecord::getVideoId,val.getId());
            List<StudyVideoRecord> record2s = recordService.list(recordWrapper2);
            if(records != null && !records.isEmpty()){
                val.setThumbsUp(records.size());
            }else{
                val.setThumbsUp(0);
            }
            if(record2s != null && !record2s.isEmpty()){
                val.setCollection(record2s.size());
            }else{
                val.setCollection(0);
            }
        });
        return list;
    }

    @ApiOperation("根据收藏数获取视频并排序")
    @GetMapping(value = "/getVideoByHot")
    public List<StudyVideo> getVideoByHot() throws Exception{
        List<StudyVideo> list = studyVideoService.getVideoByHot();
        list.forEach(val->{
            if(val.getFileId() != null){
                Object object = generalClient.getFileById(val.getFileId()).getData();
                ProjectFileDTO file = JSON.parseObject(JSON.toJSONString(object), ProjectFileDTO.class);
                val.setProjectFile(file);
            }
        });
        return list;
    }

    @ApiOperation("保存视频评论")
    @PostMapping(value = "/saveVideoNote")
    public Integer saveVideoNote(@RequestBody VideoNoteDTO videoNote,HttpServletRequest request) throws Exception{
        StudyVideoNote note = new StudyVideoNote();
        note.setVideoId(videoNote.getVideoId());
        note.setNote(videoNote.getNote());
        note.setCreatorId((Integer)request.getSession(true).getAttribute("user"));
        studyVideoNoteService.save(note);
        return note.getId();
    }

    @ApiOperation("获取视频评论")
    @GetMapping(value = "/getVideoNote/{videoId}")
    public List<StudyVideoNote> getVideoNote(@PathVariable Integer videoId) throws Exception{
        QueryWrapper<StudyVideoNote> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(StudyVideoNote::getVideoId, videoId).orderByDesc(StudyVideoNote::getCreateTime);
        List<StudyVideoNote> list = noteService.list(queryWrapper);
        if(list != null && !list.isEmpty()){
            for(StudyVideoNote videoNote: list){
                if(videoNote.getCreatorId() != null){
                    ResultVO resultVO = sysConfigClient.getUserById(videoNote.getCreatorId());
                    SysUserDTO user = JSONObject.parseObject(JSONObject.toJSONString(resultVO.getData()),SysUserDTO.class);
                    if(user != null){
                        videoNote.setUser(user.getName());
                        videoNote.setAvatar(user.getAvatar());
                    }
                }
            }
        }
        return list;
    }


}
